<?php

namespace App\Process;

use App\Logic\SignLogic;
use App\Model\VestSignQueueModel;
use co;
use EasySwoole\Component\Process\AbstractProcess;
use EasySwoole\EasySwoole\Logger;
use EasySwoole\ORM\DbManager;
use Swoole\Process;
use Throwable;

/**
 * Class VirtualMultiSignProcess
 * 虚拟用户模拟打卡出队列
 * @package App\Process
 */
class VirtualMultiSignProcess extends AbstractProcess
{
    protected function run($arg)
    {
        //当进程启动后，会执行的回调
        Logger::getInstance()->info($this->getProcessName() . " run");
        var_dump($arg);

        go(function () {
            while (true) {
                $queues = DbManager::getInstance()->invoke(function ($client) {
                    return VestSignQueueModel::invoke($client)
                        ->where('is_done', 2)
                        ->where('job_time', time(), '<=')
                        ->order('job_time', 'asc')
                        ->all();
                });

                if (count($queues) <= 0) {
                    continue;
                }

                foreach ($queues as $queue) {
                    go(function () use ($queue) {
                        $res = SignLogic::addUserSignHandle($queue->user_id, $queue->activity_id);

                        DbManager::getInstance()->invoke(function ($client) use ($queue, $res) {
                            if ($res['code'] == 200) {
                                VestSignQueueModel::invoke($client)->destroy($queue->id);
                            } else {
                                Logger::getInstance()->info('虚拟用户' . $queue->user_id . '参与' . $queue->activity_id . '签到报错:' . $res['msg']);
                            }
                        });
                    });
                }

                co::sleep(1);
            }
        });
    }

    protected function onPipeReadable(Process $process)
    {
        /*
         * 该回调可选
         * 当有主进程对子进程发送消息的时候，会触发的回调，触发后，务必使用
         * $process->read()来读取消息
         */
    }

    protected function onShutDown()
    {
        /*
         * 该回调可选
         * 当该进程退出的时候，会执行该回调
         */
    }

    protected function onException(Throwable $throwable, ...$args)
    {
        /*
         * 该回调可选
         * 当该进程出现异常的时候，会执行该回调
         */
        echo $throwable->getMessage();
    }
}
